package com.hyk.service.impl;

import com.hyk.entity.User;
import com.hyk.entity.request.UserLoginRequest;
import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import com.hyk.mapper.UserMapper;
import com.hyk.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyk.utils.MD5Utils;
import io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hyk
 * @since 2021-03-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private IUserService userService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public User login(UserLoginRequest request) {

        Object o = redisTemplate.opsForValue().get(request.getVerification());
        if (o == null){
            throw new GlobalException(ApiEnum.VERIFICATION_CODE_ERROR);
        }
        String code = (String) o;
        if (!code.equalsIgnoreCase(request.getVerificationCode())){
            throw new GlobalException(ApiEnum.VERIFICATION_CODE_ERROR);
        }
        redisTemplate.delete(request.getVerification());

//        List<User> users = userService.listByUserName(request);
//        if (users.size() > 1){
//            throw new GlobalException(ApiEnum.ABNORMAL_ACCOUNT);
//        }
//        if (users.size() < 1){
//            throw new GlobalException(ApiEnum.USERNAME_OR_PASSWORD_IS_ERROR);
//        }
//        User user = users.get(0);
        User user = userMapper.selectUser(request.getUsername());
        String encode = MD5Utils.encode(request.getPassword());
        if (user.getPassword().equals(encode)){
            return user;
        }

        return null;

    }

    @Override
    public List<User> listByUserName(UserLoginRequest request) {
        return userMapper.listByUserName(request);
    }
}
